﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using SharpGL;
using System.Runtime.InteropServices;
using System.Diagnostics;
using SharpGL.Enumerations;
using SharpGL.SceneGraph.Primitives;
using System.Numerics;
using SharpGL.SceneGraph.Assets;
using static System.Windows.Forms.LinkLabel;
using SharpGL.SceneGraph;
using System.Reflection;
using System.IO;

using RDF;
using DZJIFC.Model;
using DZJIFC.Business;

using stepengine = RDF.ifcengine;
using Scene = DZJIFC.Model.Scene;
using System.Runtime.CompilerServices;


#if _WIN64
using int_t = System.Int64;
#else
using int_t = System.Int32;
#endif


namespace DZJIFC.UI
{
    public partial class SharpGLForm : Form, IController
    {
        private readonly string title = "IFC质检";
        private DZJIFC.Model.Model _model;
        private HashSet<IView> _hsViews;
        private Point _ptPrevMousePosition;
        private bool _bInteractionInProgress;
        private ModelStructureForm _modelStructureForm;
        private ContextMenuStrip _contextMenuStrip;

        private readonly Scene _oglScene = new Scene();

        // 新增：IFC构件分类视图管理器
        private IModelStructureView _ifcBuildStructureView;
        private ModelStructureViewFactory.ViewType _currentViewType = ModelStructureViewFactory.ViewType.Enhanced;

        // 新增：当前选中的IFC实例及其属性
        private IInstance _currentSelectedInstance;
        private Dictionary<string, List<IFCProperty>> _propertyCategories;

        public SharpGLForm()
        {
            InitializeComponent();
            InitializeMenu();

            // Rotate, Move, Zoom
            _ptPrevMousePosition = new Point(-1, -1);
            _bInteractionInProgress = false;

            // ICController
            _hsViews = new HashSet<IView>();

            // Model Structure
            _modelStructureForm = new ModelStructureForm();
            _modelStructureForm.SetController(this);
            _modelStructureForm.Show(this);

            // 初始化TrView_IFCBuid的事件处理
            InitializeTrViewIFCBuid();

            // 初始化Lv_IfcPro ListView
            InitializeLvIfcPro();

            // 初始化属性分类字典
            _propertyCategories = new Dictionary<string, List<IFCProperty>>();
        }

        /// <summary>
        /// 初始化Lv_IfcPro ListView控件的属性展示功能
        /// Initialize property display functionality for Lv_IfcPro ListView control
        /// </summary>
        private void InitializeLvIfcPro()
        {
            // 设置ListView属性
            Lv_IfcPro.View = View.Details;
            Lv_IfcPro.FullRowSelect = true;
            Lv_IfcPro.GridLines = true;
            Lv_IfcPro.HeaderStyle = ColumnHeaderStyle.Nonclickable;
            Lv_IfcPro.MultiSelect = false;

            // 添加列标题
            Lv_IfcPro.Columns.Clear();
            Lv_IfcPro.Columns.Add("属性分类 (Category)", 150);
            Lv_IfcPro.Columns.Add("属性名称 (Property)", 180);
            Lv_IfcPro.Columns.Add("属性值 (Value)", 200);
            Lv_IfcPro.Columns.Add("单位 (Unit)", 80);
            Lv_IfcPro.Columns.Add("数据类型 (Type)", 100);

            // 绑定事件
            Lv_IfcPro.SelectedIndexChanged += Lv_IfcPro_SelectedIndexChanged;
            Lv_IfcPro.MouseDoubleClick += Lv_IfcPro_MouseDoubleClick;

            // 创建右键菜单
            CreateLvIfcProContextMenu();
        }

        /// <summary>
        /// 创建Lv_IfcPro的右键上下文菜单
        /// Create context menu for Lv_IfcPro
        /// </summary>
        private void CreateLvIfcProContextMenu()
        {
            var contextMenu = new ContextMenuStrip();

            // 复制属性值
            var copyValueMenuItem = new ToolStripMenuItem("复制属性值 (Copy Value)");
            copyValueMenuItem.Click += (s, e) => CopySelectedPropertyValue();

            // 复制所有属性
            var copyAllMenuItem = new ToolStripMenuItem("复制所有属性 (Copy All Properties)");
            copyAllMenuItem.Click += (s, e) => CopyAllProperties();

            // 导出属性到文件
            var exportMenuItem = new ToolStripMenuItem("导出属性 (Export Properties)");
            exportMenuItem.Click += (s, e) => ExportPropertiesToFile();

            // 按类型筛选
            var filterByTypeMenuItem = new ToolStripMenuItem("按类型筛选 (Filter by Type)");
            filterByTypeMenuItem.Click += (s, e) => FilterPropertiesByType();

            // 显示所有属性
            var showAllMenuItem = new ToolStripMenuItem("显示所有属性 (Show All)");
            showAllMenuItem.Click += (s, e) => ShowAllProperties();

            contextMenu.Items.AddRange(new ToolStripItem[] {
                copyValueMenuItem,
                copyAllMenuItem,
                new ToolStripSeparator(),
                exportMenuItem,
                new ToolStripSeparator(),
                filterByTypeMenuItem,
                showAllMenuItem
            });

            Lv_IfcPro.ContextMenuStrip = contextMenu;
        }

        #region Lv_IfcPro 事件处理器

        private void Lv_IfcPro_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (Lv_IfcPro.SelectedItems.Count > 0)
            {
                var selectedItem = Lv_IfcPro.SelectedItems[0];
                var propertyInfo = selectedItem.Tag as IFCProperty;
                
                if (propertyInfo != null)
                {
                    // 可以在这里添加属性详细信息的显示逻辑
                    // 例如在状态栏或工具提示中显示更多信息
                    UpdatePropertyStatusInfo(propertyInfo);
                }
            }
        }

        private void Lv_IfcPro_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            if (Lv_IfcPro.SelectedItems.Count > 0)
            {
                var selectedItem = Lv_IfcPro.SelectedItems[0];
                var propertyInfo = selectedItem.Tag as IFCProperty;
                
                if (propertyInfo != null)
                {
                    // 双击时显示属性详细信息对话框
                    ShowPropertyDetailDialog(propertyInfo);
                }
            }
        }

        #endregion

        #region IFC属性加载和显示方法

        /// <summary>
        /// 装载选中IFC实例的属性到ListView
        /// Load properties of selected IFC instance to ListView
        /// </summary>
        /// <param name="instance">选中的IFC实例</param>
        public void LoadInstancePropertiesToListView(IInstance instance)
        {
            _currentSelectedInstance = instance;
            Lv_IfcPro.Items.Clear();
            _propertyCategories.Clear();

            if (instance == null || _model?.Type != ModelType.IFC)
            {
                // 清空时重置标题
                UpdatePanelTitles(null, null);
                return;
            }

            try
            {
                var ifcModel = _model as IFCModel;
                if (ifcModel != null && ifcModel.IFCInstances.ContainsKey(instance.Geometry.Instance))
                {
                    var ifcInstance = ifcModel.IFCInstances[instance.Geometry.Instance];
                    
                    // 获取构件基本信息
                    string componentType = GetComponentTypeName(instance.Geometry.Instance);
                    string componentName = GetComponentName(instance.Geometry.Instance);
                    
                    // 更新标题显示当前选中的构件信息
                    UpdatePanelTitles(componentType, componentName);
                    
                    // 提取基础属性
                    ExtractBasicProperties(instance.Geometry.Instance);
                    
                    // 提取属性集属性
                    ExtractPropertySetProperties(instance.Geometry.Instance);
                    
                    // 提取数量属性
                    ExtractQuantityProperties(instance.Geometry.Instance);
                    
                    // 提取材料属性
                    ExtractMaterialProperties(instance.Geometry.Instance);
                    
                    // 提取几何属性
                    ExtractGeometryProperties(instance.Geometry.Instance);

                    // 显示属性到ListView
                    DisplayPropertiesInListView();

                    // 更新状态信息
                    UpdatePropertyCountInfo();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"加载属性时发生错误：{ex.Message}", "错误", 
                               MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// 获取构件类型名称（中英文）
        /// Get component type name (Chinese and English)
        /// </summary>
        private string GetComponentTypeName(int_t iInstance)
        {
            int_t iType = stepengine.sdaiGetInstanceType(iInstance);
            stepengine.engiGetEntityName(iType, stepengine.sdaiUNICODE, out IntPtr type);
            string ifcType = Marshal.PtrToStringUni(type) ?? "Unknown";
            
            string chineseType = GetChineseTypeName(ifcType);
            return $"{chineseType} ({ifcType})";
        }

        /// <summary>
        /// 获取构件名称
        /// Get component name
        /// </summary>
        private string GetComponentName(int_t iInstance)
        {
            stepengine.sdaiGetAttrBN(iInstance, "Name", stepengine.sdaiUNICODE, out IntPtr name);
            string componentName = Marshal.PtrToStringUni(name) ?? "";
            
            if (string.IsNullOrEmpty(componentName))
            {
                // 如果没有名称，使用Express ID
                long expressId = stepengine.internalGetP21Line(iInstance);
                componentName = $"#{expressId}";
            }
            
            return componentName;
        }

        /// <summary>
        /// 获取IFC类型的中文名称
        /// Get Chinese name of IFC type
        /// </summary>
        private string GetChineseTypeName(string ifcType)
        {
            return ifcType.ToUpper() switch
            {
                "IFCWALL" => "墙体",
                "IFCCOLUMN" => "柱子", 
                "IFCBEAM" => "梁",
                "IFCSLAB" => "楼板",
                "IFCDOOR" => "门",
                "IFCWINDOW" => "窗",
                "IFCSTAIR" => "楼梯",
                "IFCRAILING" => "栏杆",
                "IFCROOF" => "屋顶",
                "IFCPLATE" => "板",
                "IFCMEMBER" => "构件",
                "IFCBUILDINGELEMENTPROXY" => "建筑构件代理",
                "IFCCURTAINWALL" => "幕墙",
                "IFCFOOTING" => "基础",
                "IFCSPACE" => "空间",
                "IFCCOVERING" => "覆盖层",
                "IFCCEILING" => "吊顶",
                "IFCRAMP" => "坡道",
                "IFCFLOWTERMINAL" => "流体终端",
                "IFCDISTRIBUTIONELEMENT" => "分配构件",
                "IFCFURNISHINGELEMENT" => "家具构件",
                "IFCTRANSPORTELEMENT" => "运输构件",
                "IFCVIRTUALELEMENT" => "虚拟构件",
                "IFCOPENINGELEMENT" => "开口构件",
                "IFCELECTRICALELEMENT" => "电气构件",
                "IFCEQUIPMENTELEMENT" => "设备构件",
                "IFCFEATUREELEMENT" => "特征构件",
                "IFCREINFORCINGBAR" => "钢筋",
                "IFCREINFORCINGMESH" => "钢筋网",
                "IFCTENDON" => "预应力筋",
                "IFCTENDONANCHOR" => "预应力锚具",
                _ => "其他构件"
            };
        }

        /// <summary>
        /// 更新面板标题显示当前选中的构件信息
        /// Update panel titles to show current selected component info
        /// </summary>
        private void UpdatePanelTitles(string componentType, string componentName)
        {
            if (string.IsNullOrEmpty(componentType) || string.IsNullOrEmpty(componentName))
            {
                // 未选中构件时显示默认标题
                lblTreeViewTitle.Text = "🏗️ IFC 构件结构 (IFC Component Structure)";
                lblPropertyTitle.Text = "📋 IFC 构件属性 (IFC Component Properties)";
            }
            else
            {
                // 选中构件时显示具体信息
                lblTreeViewTitle.Text = $"🏗️ IFC 构件结构 - 已选中: {componentName}";
                lblPropertyTitle.Text = $"📋 {componentType} - {componentName}";
                
                // 统计属性数量
                int totalProperties = _propertyCategories.Sum(c => c.Value.Count);
                if (totalProperties > 0)
                {
                    lblPropertyTitle.Text += $" ({totalProperties} 个属性)";
                }
            }
        }
        #endregion

        #region Lv_IfcPro 操作方法

        /// <summary>
        /// 复制选中的属性值
        /// Copy selected property value
        /// </summary>
        private void CopySelectedPropertyValue()
        {
            if (Lv_IfcPro.SelectedItems.Count > 0)
            {
                var selectedItem = Lv_IfcPro.SelectedItems[0];
                var propertyInfo = selectedItem.Tag as IFCProperty;
                
                if (propertyInfo != null)
                {
                    string textToCopy = $"{propertyInfo.DisplayName}: {propertyInfo.Value}";
                    if (!string.IsNullOrEmpty(propertyInfo.Unit))
                    {
                        textToCopy += $" {propertyInfo.Unit}";
                    }
                    
                    Clipboard.SetText(textToCopy);
                    MessageBox.Show("属性值已复制到剪贴板", "信息", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
        }

        /// <summary>
        /// 复制所有属性
        /// Copy all properties
        /// </summary>
        private void CopyAllProperties()
        {
            if (_currentSelectedInstance == null) return;

            var sb = new StringBuilder();
            sb.AppendLine($"IFC组件属性 - {DateTime.Now:yyyy-MM-dd HH:mm:ss}");
            sb.AppendLine(new string('=', 50));

            foreach (var category in _propertyCategories)
            {
                sb.AppendLine($"\n[{category.Key}]");
                foreach (var property in category.Value)
                {
                    sb.AppendLine($"{property.DisplayName}: {property.Value}" + 
                                (string.IsNullOrEmpty(property.Unit) ? "" : $" {property.Unit}"));
                }
            }

            Clipboard.SetText(sb.ToString());
            MessageBox.Show("所有属性已复制到剪贴板", "信息", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }

        /// <summary>
        /// 导出属性到文件
        /// Export properties to file
        /// </summary>
        private void ExportPropertiesToFile()
        {
            if (_currentSelectedInstance == null) return;

            using (var sfd = new SaveFileDialog())
            {
                sfd.Title = "导出属性到文件";
                sfd.Filter = "文本文件 (*.txt)|*.txt|CSV文件 (*.csv)|*.csv";
                sfd.DefaultExt = "txt";
                sfd.FileName = $"IFC_Properties_{DateTime.Now:yyyyMMdd_HHmmss}";

                if (sfd.ShowDialog() == DialogResult.OK)
                {
                    try
                    {
                        if (sfd.FilterIndex == 1) // TXT格式
                        {
                            ExportToTextFile(sfd.FileName);
                        }
                        else // CSV格式
                        {
                            ExportToCsvFile(sfd.FileName);
                        }

                        MessageBox.Show($"属性已成功导出到：{sfd.FileName}", "导出成功", 
                                       MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show($"导出失败：{ex.Message}", "错误", 
                                       MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
            }
        }

        /// <summary>
        /// 导出到文本文件
        /// Export to text file
        /// </summary>
        private void ExportToTextFile(string filePath)
        {
            using (var writer = new StreamWriter(filePath, false, Encoding.UTF8))
            {
                writer.WriteLine($"IFC组件属性导出 - {DateTime.Now:yyyy-MM-dd HH:mm:ss}");
                writer.WriteLine(new string('=', 60));
                writer.WriteLine();

                foreach (var category in _propertyCategories)
                {
                    writer.WriteLine($"[{category.Key}]");
                    writer.WriteLine(new string('-', category.Key.Length + 2));
                    
                    foreach (var property in category.Value)
                    {
                        writer.WriteLine($"属性名称: {property.DisplayName}");
                        writer.WriteLine($"属性值:   {property.Value}");
                        if (!string.IsNullOrEmpty(property.Unit))
                        {
                            writer.WriteLine($"单位:     {property.Unit}");
                        }
                        writer.WriteLine($"类型:     {property.Type}");
                        if (!string.IsNullOrEmpty(property.Description))
                        {
                            writer.WriteLine($"描述:     {property.Description}");
                        }
                        writer.WriteLine();
                    }
                    writer.WriteLine();
                }
            }
        }

        /// <summary>
        /// 导出到CSV文件
        /// Export to CSV file
        /// </summary>
        private void ExportToCsvFile(string filePath)
        {
            using (var writer = new StreamWriter(filePath, false, Encoding.UTF8))
            {
                // 写入CSV标题
                writer.WriteLine("分类,属性名称,属性值,单位,类型,描述");

                foreach (var category in _propertyCategories)
                {
                    foreach (var property in category.Value)
                    {
                        writer.WriteLine($"\"{category.Key}\",\"{property.DisplayName}\",\"{property.Value}\"," +
                                       $"\"{property.Unit}\",\"{property.Type}\",\"{property.Description}\"");
                    }
                }
            }
        }

        /// <summary>
        /// 按类型筛选属性
        /// Filter properties by type
        /// </summary>
        private void FilterPropertiesByType()
        {
            // 创建筛选对话框
            var filterForm = new Form()
            {
                Text = "按类型筛选属性",
                Size = new Size(300, 200),
                StartPosition = FormStartPosition.CenterParent
            };

            var comboBox = new System.Windows.Forms.ComboBox()
            {
                Location = new Point(20, 30),
                Size = new Size(200, 25),
                DropDownStyle = ComboBoxStyle.DropDownList
            };

            // 添加筛选选项
            comboBox.Items.Add("全部属性");
            comboBox.Items.Add("基础属性");
            comboBox.Items.Add("属性集");
            comboBox.Items.Add("数量属性");
            comboBox.Items.Add("材料属性");
            comboBox.Items.Add("几何属性");
            comboBox.SelectedIndex = 0;

            var okButton = new System.Windows.Forms.Button()
            {
                Text = "确定",
                Location = new Point(50, 80),
                Size = new Size(75, 25),
                DialogResult = DialogResult.OK
            };

            var cancelButton = new System.Windows.Forms.Button()
            {
                Text = "取消",
                Location = new Point(150, 80),
                Size = new Size(75, 25),
                DialogResult = DialogResult.Cancel
            };

            filterForm.Controls.AddRange(new Control[] { comboBox, okButton, cancelButton });

            if (filterForm.ShowDialog() == DialogResult.OK)
            {
                FilterPropertiesBySelectedType(comboBox.SelectedItem.ToString());
            }
        }

        /// <summary>
        /// 根据选择的类型筛选属性
        /// Filter properties by selected type
        /// </summary>
        private void FilterPropertiesBySelectedType(string selectedType)
        {
            Lv_IfcPro.Items.Clear();

            var filteredCategories = _propertyCategories;

            if (selectedType != "全部属性")
            {
                filteredCategories = _propertyCategories.Where(c =>
                {
                    return selectedType switch
                    {
                        "基础属性" => c.Key.Contains("基础属性"),
                        "属性集" => c.Key.Contains("Pset_") || (c.Key.Contains("属性") && !c.Key.Contains("基础") && !c.Key.Contains("数量") && !c.Key.Contains("材料") && !c.Key.Contains("几何")),
                        "数量属性" => c.Key.Contains("Quantities") || c.Key.Contains("数量"),
                        "材料属性" => c.Key.Contains("Material") || c.Key.Contains("材料"),
                        "几何属性" => c.Key.Contains("Geometry") || c.Key.Contains("几何"),
                        _ => true
                    };
                }).ToDictionary(c => c.Key, c => c.Value);
            }

            // 显示筛选后的属性
            foreach (var category in filteredCategories)
            {
                string categoryName = category.Key;
                var properties = category.Value;

                var categoryItem = new ListViewItem(categoryName);
                categoryItem.SubItems.Add("");
                categoryItem.SubItems.Add($"[{properties.Count} 个属性]");
                categoryItem.SubItems.Add("");
                categoryItem.SubItems.Add("Category");
                categoryItem.Font = new Font(Lv_IfcPro.Font, FontStyle.Bold);
                categoryItem.BackColor = Color.LightGray;
                Lv_IfcPro.Items.Add(categoryItem);

                foreach (var property in properties)
                {
                    var propertyItem = new ListViewItem($"  {categoryName}");
                    propertyItem.SubItems.Add(property.DisplayName);
                    propertyItem.SubItems.Add(property.Value);
                    propertyItem.SubItems.Add(property.Unit);
                    propertyItem.SubItems.Add(property.Type);
                    propertyItem.Tag = property;
                    Lv_IfcPro.Items.Add(propertyItem);
                }
            }

            // 自动调整列宽
            for (int i = 0; i < Lv_IfcPro.Columns.Count; i++)
            {
                Lv_IfcPro.AutoResizeColumn(i, ColumnHeaderAutoResizeStyle.ColumnContent);
            }
        }

        /// <summary>
        /// 显示所有属性
        /// Show all properties
        /// </summary>
        private void ShowAllProperties()
        {
            DisplayPropertiesInListView();
        }

        /// <summary>
        /// 更新属性状态信息
        /// Update property status information
        /// </summary>
        private void UpdatePropertyStatusInfo(IFCProperty property)
        {
            // 可以在状态栏或其他地方显示详细信息
            // 这里只是示例，具体实现根据需要
        }

        /// <summary>
        /// 显示属性详细信息对话框
        /// Show property detail dialog
        /// </summary>
        private void ShowPropertyDetailDialog(IFCProperty property)
        {
            var detailForm = new Form()
            {
                Text = "属性详细信息",
                Size = new Size(400, 300),
                StartPosition = FormStartPosition.CenterParent
            };

            var textBox = new System.Windows.Forms.TextBox()
            {
                Location = new Point(20, 20),
                Size = new Size(340, 200),
                Multiline = true,
                ReadOnly = true,
                ScrollBars = ScrollBars.Vertical
            };

            var sb = new StringBuilder();
            sb.AppendLine($"属性名称: {property.DisplayName}");
            sb.AppendLine($"内部名称: {property.InternalName}");
            sb.AppendLine($"属性值: {property.Value}");
            sb.AppendLine($"单位: {property.Unit}");
            sb.AppendLine($"数据类型: {property.Type}");
            if (!string.IsNullOrEmpty(property.Description))
            {
                sb.AppendLine($"描述: {property.Description}");
            }

            textBox.Text = sb.ToString();

            var closeButton = new System.Windows.Forms.Button()
            {
                Text = "关闭",
                Location = new Point(160, 240),
                Size = new Size(75, 25),
                DialogResult = DialogResult.OK
            };

            detailForm.Controls.AddRange(new Control[] { textBox, closeButton });
            detailForm.ShowDialog();
        }

        /// <summary>
        /// 更新属性数量信息
        /// Update property count information
        /// </summary>
        private void UpdatePropertyCountInfo()
        {
            int totalProperties = _propertyCategories.Sum(c => c.Value.Count);
            
            // 更新属性标题，显示属性总数
            if (_currentSelectedInstance != null)
            {
                string componentType = GetComponentTypeName(_currentSelectedInstance.Geometry.Instance);
                string componentName = GetComponentName(_currentSelectedInstance.Geometry.Instance);
                lblPropertyTitle.Text = $"📋 {componentType} - {componentName} ({totalProperties} 个属性)";
            }
        }

        #endregion

        /// <summary>
        /// 初始化TrView_IFCBuid控件的分类装载功能
        /// Initialize classification loading functionality for TrView_IFCBuid control
        /// </summary>
        private void InitializeTrViewIFCBuid()
        {
            // 设置TreeView属性
            TrView_IFCBuid.FullRowSelect = true;
            TrView_IFCBuid.HideSelection = false;
            TrView_IFCBuid.ShowNodeToolTips = true;
            TrView_IFCBuid.DrawMode = TreeViewDrawMode.OwnerDrawText;

            // 绑定事件处理器
            TrView_IFCBuid.NodeMouseClick += TrView_IFCBuid_NodeMouseClick;
            TrView_IFCBuid.AfterSelect += TrView_IFCBuid_AfterSelect;
            TrView_IFCBuid.BeforeExpand += TrView_IFCBuid_BeforeExpand;
            TrView_IFCBuid.DrawNode += TrView_IFCBuid_DrawNode;

            // 创建右键菜单
            CreateTrViewContextMenu();
        }

        /// <summary>
        /// 创建TrView_IFCBuid的右键上下文菜单
        /// Create context menu for TrView_IFCBuid
        /// </summary>
        private void CreateTrViewContextMenu()
        {
            var contextMenu = new ContextMenuStrip();
            
            // 视图切换菜单项
            var viewModeMenuItem = new ToolStripMenuItem("视图模式 (View Mode)");
            
            var traditionalMenuItem = new ToolStripMenuItem("传统结构 (Traditional)");
            traditionalMenuItem.Click += (s, e) => SwitchToViewMode(ModelStructureViewFactory.ViewType.Traditional);
            
            var spaceBasedMenuItem = new ToolStripMenuItem("空间分类 (Space Based)");
            spaceBasedMenuItem.Click += (s, e) => SwitchToViewMode(ModelStructureViewFactory.ViewType.SpaceBased);
            
            var propertyBasedMenuItem = new ToolStripMenuItem("属性分类 (Property Based)");
            propertyBasedMenuItem.Click += (s, e) => SwitchToViewMode(ModelStructureViewFactory.ViewType.PropertyBased);
            
            var enhancedMenuItem = new ToolStripMenuItem("增强视图 (Enhanced)");
            enhancedMenuItem.Click += (s, e) => SwitchToViewMode(ModelStructureViewFactory.ViewType.Enhanced);
            enhancedMenuItem.Checked = true; // 默认选中

            viewModeMenuItem.DropDownItems.AddRange(new ToolStripItem[] { 
                traditionalMenuItem, spaceBasedMenuItem, propertyBasedMenuItem, enhancedMenuItem 
            });

            // 操作菜单项
            var expandAllMenuItem = new ToolStripMenuItem("展开全部 (Expand All)");
            expandAllMenuItem.Click += (s, e) => TrView_IFCBuid.ExpandAll();
            
            var collapseAllMenuItem = new ToolStripMenuItem("折叠全部 (Collapse All)");
            collapseAllMenuItem.Click += (s, e) => TrView_IFCBuid.CollapseAll();

            var refreshMenuItem = new ToolStripMenuItem("刷新 (Refresh)");
            refreshMenuItem.Click += (s, e) => RefreshTrViewIFCBuid();

            // 构件操作菜单项
            var zoomToMenuItem = new ToolStripMenuItem("缩放到构件 (Zoom To)");
            zoomToMenuItem.Click += (s, e) => ZoomToSelectedComponent();

            var hideComponentMenuItem = new ToolStripMenuItem("隐藏构件 (Hide Component)");
            hideComponentMenuItem.Click += (s, e) => ToggleComponentVisibility(false);

            var showComponentMenuItem = new ToolStripMenuItem("显示构件 (Show Component)");
            showComponentMenuItem.Click += (s, e) => ToggleComponentVisibility(true);

            contextMenu.Items.AddRange(new ToolStripItem[] {
                viewModeMenuItem,
                new ToolStripSeparator(),
                expandAllMenuItem,
                collapseAllMenuItem,
                refreshMenuItem,
                new ToolStripSeparator(),
                zoomToMenuItem,
                hideComponentMenuItem,
                showComponentMenuItem
            });

            TrView_IFCBuid.ContextMenuStrip = contextMenu;
        }

        /// <summary>
        /// 切换视图模式
        /// Switch view mode
        /// </summary>
        private void SwitchToViewMode(ModelStructureViewFactory.ViewType viewType)
        {
            _currentViewType = viewType;
            
            if (_model != null)
            {
                LoadIFCComponentsToTreeView();
            }

            // 更新菜单选中状态
            UpdateViewModeMenuSelection(viewType);
        }

        /// <summary>
        /// 更新视图模式菜单的选中状态
        /// Update view mode menu selection
        /// </summary>
        private void UpdateViewModeMenuSelection(ModelStructureViewFactory.ViewType selectedType)
        {
            var contextMenu = TrView_IFCBuid.ContextMenuStrip;
            if (contextMenu?.Items[0] is ToolStripMenuItem viewModeMenuItem)
            {
                foreach (ToolStripMenuItem item in viewModeMenuItem.DropDownItems)
                {
                    item.Checked = false;
                }

                var index = selectedType switch
                {
                    ModelStructureViewFactory.ViewType.Traditional => 0,
                    ModelStructureViewFactory.ViewType.SpaceBased => 1,
                    ModelStructureViewFactory.ViewType.PropertyBased => 2,
                    ModelStructureViewFactory.ViewType.Enhanced => 3,
                    _ => 3
                };

                if (index < viewModeMenuItem.DropDownItems.Count)
                {
                    ((ToolStripMenuItem)viewModeMenuItem.DropDownItems[index]).Checked = true;
                }
            }
        }

        /// <summary>
        /// 将IFC构件分类装载到TrView_IFCBuid树形控件中
        /// Load IFC components with classification into TrView_IFCBuid tree control
        /// </summary>
        private void LoadIFCComponentsToTreeView()
        {
            if (_model?.Type != ModelType.IFC) return;

            try
            {
                // 清空现有节点
                TrView_IFCBuid.Nodes.Clear();

                // 创建对应类型的模型结构视图
                _ifcBuildStructureView = ModelStructureViewFactory.CreateView(
                    _currentViewType, 
                    this, 
                    TrView_IFCBuid, 
                    TrView_IFCBuid.ContextMenuStrip);

                // 装载模型数据
                _ifcBuildStructureView.OnModelLoaded();

                // 展开第一级节点
                if (TrView_IFCBuid.Nodes.Count > 0)
                {
                    TrView_IFCBuid.Nodes[0].Expand();
                }

                // 更新状态栏信息（如果有的话）
                UpdateStatusBarInfo();
            }
            catch (Exception ex)
            {
                MessageBox.Show($"装载IFC构件时发生错误：{ex.Message}", "错误", 
                               MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// 更新状态栏信息
        /// Update status bar information
        /// </summary>
        private void UpdateStatusBarInfo()
        {
            var statistics = GetComponentStatistics();
            
            // 这里可以更新状态栏或标题栏显示统计信息
            // 例如：构件总数、按类型分组的数量等
            var title = $"{Path.GetFileNameWithoutExtension(_model?.FilePath)} - {this.title}";
            if (statistics.ContainsKey("TotalComponents"))
            {
                title += $" - 共 {statistics["TotalComponents"]} 个构件";
            }
            this.Text = title;
        }

        /// <summary>
        /// 获取构件统计信息
        /// Get component statistics
        /// </summary>
        private Dictionary<string, object> GetComponentStatistics()
        {
            var stats = new Dictionary<string, object>();
            
            if (_model?.Type == ModelType.IFC)
            {
                var ifcModel = _model as IFCModel;
                if (ifcModel != null)
                {
                    // 统计各类型构件数量
                    var componentTypes = new[] { 
                        "IfcWall", "IfcColumn", "IfcBeam", "IfcSlab", "IfcDoor", "IfcWindow", 
                        "IfcStair", "IfcRailing", "IfcRoof", "IfcSpace"
                    };

                    int totalCount = 0;
                    foreach (var type in componentTypes)
                    {
                        var entityID = stepengine.sdaiGetEntityExtentBN(ifcModel.Instance, type);
                        var count = stepengine.sdaiGetMemberCount(entityID);
                        stats[type] = count;
                        totalCount += (int)count;
                    }
                    
                    stats["TotalComponents"] = totalCount;
                }
            }
            
            return stats;
        }

        #region TrView_IFCBuid 事件处理器

        private void TrView_IFCBuid_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e)
        {
            _ifcBuildStructureView?.TreeView_OnNodeMouseClick(sender, e);
        }

        private void TrView_IFCBuid_AfterSelect(object sender, TreeViewEventArgs e)
        {
            _ifcBuildStructureView?.TreeView_AfterSelect(sender, e);
        }

        private void TrView_IFCBuid_BeforeExpand(object sender, TreeViewCancelEventArgs e)
        {
            _ifcBuildStructureView?.TreeView_BeforeExpand(sender, e);
        }

        private void TrView_IFCBuid_DrawNode(object sender, DrawTreeNodeEventArgs e)
        {
            var bSelected = (e.State & TreeNodeStates.Selected) == TreeNodeStates.Selected;
            if (bSelected)
            {
                using (var selectedBrush = new SolidBrush(Color.Red))
                {
                    e.Graphics.FillRectangle(selectedBrush, e.Bounds);
                    var font = e.Node.NodeFont ?? e.Node.TreeView.Font;
                    TextRenderer.DrawText(e.Graphics, e.Node.Text, font, e.Bounds, 
                                        SystemColors.HighlightText, TextFormatFlags.GlyphOverhangPadding);
                }
            }
            else
            {
                e.DrawDefault = true;
            }
        }

        #endregion

        #region TrView_IFCBuid 操作方法

        /// <summary>
        /// 刷新TrView_IFCBuid控件
        /// Refresh TrView_IFCBuid control
        /// </summary>
        private void RefreshTrViewIFCBuid()
        {
            LoadIFCComponentsToTreeView();
        }

        /// <summary>
        /// 缩放到选中的构件
        /// Zoom to selected component
        /// </summary>
        private void ZoomToSelectedComponent()
        {
            var selectedInstance = _ifcBuildStructureView?.GetSelectedInstance();
            if (selectedInstance != null)
            {
                ZoomTo(selectedInstance);
            }
        }

        /// <summary>
        /// 切换构件的可见性
        /// Toggle component visibility
        /// </summary>
        private void ToggleComponentVisibility(bool visible)
        {
            var selectedInstance = _ifcBuildStructureView?.GetSelectedInstance();
            if (selectedInstance != null)
            {
                selectedInstance.Enabled = visible;
                // 刷新视图
                RefreshTrViewIFCBuid();
            }
        }

        #endregion

        private void InitializeMenu()
        {
            var zoomToMenuItem = new ToolStripMenuItem();
            zoomToMenuItem.Text = "Zoom To";
            zoomToMenuItem.Click += ZoomToMenuItem_Click;
            var zoomExtentMenuItem = new ToolStripMenuItem();
            zoomExtentMenuItem.Text = "Zoom Extent";
            zoomExtentMenuItem.Click += ZoomExtentMenuItem_Click;

            _contextMenuStrip = new ContextMenuStrip();
            _contextMenuStrip.Items.AddRange(new ToolStripMenuItem[] { zoomToMenuItem, zoomExtentMenuItem });
            _contextMenuStrip.Opening += _contextMenuStrip_Opening;

            openGLControl.ContextMenuStrip = _contextMenuStrip;
        }

        void _contextMenuStrip_Opening(object sender, System.ComponentModel.CancelEventArgs e)
        {
            var zoomToMenuItem = _contextMenuStrip.Items[0];
            zoomToMenuItem.Enabled = (Model != null) && (_oglScene.SelectedInstance != null);

            var zoomExtentMenuItem = _contextMenuStrip.Items[1];
            zoomExtentMenuItem.Enabled = Model != null;

            e.Cancel = false;
        }

        private void ZoomToMenuItem_Click(object sender, EventArgs e)
        {
            ZoomTo(_oglScene.SelectedInstance);
        }

        private void ZoomExtentMenuItem_Click(object sender, EventArgs e)
        {
            ZoomExtent();
        }

        public void OnModelLoaded()
        {
            OpenGL gl = openGLControl.OpenGL;

            _oglScene.OnModelLoaded(_model);

            foreach (var prGeometry in _model.Geometries)
            {
                foreach (var cohort in prGeometry.Value.ConcFacePolygonsVerticesCohorts)
                {
                    cohort.Initialize(gl);
                }

                foreach (var cohort in prGeometry.Value.ConcFacesVerticesCohorts)
                {
                    cohort.Initialize(gl);
                }

                foreach (var cohort in prGeometry.Value.LinesVerticesCohorts)
                {
                    cohort.Initialize(gl);
                }

                foreach (var cohort in prGeometry.Value.PointsVerticesCohorts)
                {
                    cohort.Initialize(gl);
                }
            }

            // 新增：装载IFC构件到TrView_IFCBuid
            if (_model.Type == ModelType.IFC)
            {
                LoadIFCComponentsToTreeView();
            }
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }

            base.Dispose(disposing);
        }

        private void Reset()
        {
            if (_model != null)
            {
                stepengine.sdaiCloseModel(_model.Instance);

                OpenGL gl = openGLControl.OpenGL;

                foreach (var prGeometry in _model.Geometries)
                {
                    foreach (var cohort in prGeometry.Value.ConcFacePolygonsVerticesCohorts)
                    {
                        cohort.Delete(gl);
                    }

                    foreach (var cohort in prGeometry.Value.ConcFacesVerticesCohorts)
                    {
                        cohort.Delete(gl);
                    }

                    foreach (var cohort in prGeometry.Value.LinesVerticesCohorts)
                    {
                        cohort.Delete(gl);
                    }

                    foreach (var cohort in prGeometry.Value.PointsVerticesCohorts)
                    {
                        cohort.Delete(gl);
                    }
                }

                _model = null;
            }

            // 清空TrView_IFCBuid
            TrView_IFCBuid.Nodes.Clear();
            _ifcBuildStructureView = null;

            _ptPrevMousePosition = new Point(-1, -1);
            _bInteractionInProgress = false;
        }

        private void openGLControl_OpenGLDraw(object sender, RenderEventArgs e)
        {
            _oglScene.Draw(openGLControl);
        }

        private void openGLControl_OpenGLInitialized(object sender, EventArgs e)
        {
            _oglScene.Initialize(openGLControl.OpenGL, this, typeof(SharpGLForm).Assembly);
        }

        private void openGLControl_Resized(object sender, EventArgs e)
        {
            _oglScene.OnResize(openGLControl.OpenGL, (float)openGLControl.Width, (float)openGLControl.Height);
        }

        private void openToolStripMenuItem_Click(object sender, EventArgs e)
        {
            OpenFileDialog dialog = new OpenFileDialog();
            dialog.Filter = "STEP Files (*.stp; *.step; *.ifc)|*.stp;*.step; *.ifc|All Files (*.*)|*.*||";
            dialog.Title = "Open";

            if (dialog.ShowDialog() != DialogResult.OK)
            {
                return;
            }

            if (CreateModel(dialog.FileName) && LoadModel(dialog.FileName))
            {
                return;
            }

            MessageBox.Show("Unknown model.", "Error",
                MessageBoxButtons.OK, MessageBoxIcon.Error,
                MessageBoxDefaultButton.Button1,
                MessageBoxOptions.DefaultDesktopOnly, false);
        }

        private bool CreateModel(string strFilePath)
        {
            Reset();

            var strExtension = Path.GetExtension(strFilePath).ToUpper();
            if ((strExtension == ".STEP") || (strExtension == ".STP"))
            {
                _model = new AP242Model();
            }
            else if (strExtension == ".IFC")
            {
                _model = new IFCModel();
            }
            else
            {
                return false;
            }

            _model.ModelLoaded += (s, e) =>
            {
                OnModelLoaded();

                foreach (var ifcView in _hsViews)
                {
                    ifcView.OnModelLoaded();
                }
            };

            return true;
        }

        private bool LoadModel(string strFilePath)
        {
            if ((_model != null) && _model.Load(strFilePath))
            {
                this.Text = string.Format($"{Path.GetFileNameWithoutExtension(strFilePath)} - {title}");

                return true;
            }

            return false;
        }

        private void exitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Close();
        }

        private void openGLControl_MouseUp(object sender, MouseEventArgs e)
        {
            _ptPrevMousePosition = new Point(-1, -1);

            /*
	        * Selection
	        */
            if (!_bInteractionInProgress)
            {
                _oglScene.SelectInstance(openGLControl, e.Location);
            }

            _bInteractionInProgress = false;
        }

        private void openGLControl_MouseDown(object sender, MouseEventArgs e)
        {
            OpenGL gl = openGLControl.OpenGL;

            _ptPrevMousePosition = e.Location;
        }

        private void openGLControl_MouseMove(object sender, MouseEventArgs e)
        {
            OpenGL gl = openGLControl.OpenGL;

            // Selection
            _oglScene.PointInstance(openGLControl, e.Location, _bInteractionInProgress);

            if (_ptPrevMousePosition.X == -1)
            {
                return;
            }

            // Rotate
            if ((e.Button & MouseButtons.Left) == MouseButtons.Left)
            {
                _bInteractionInProgress = true;

                float fXAngle = ((float)e.Location.Y - (float)_ptPrevMousePosition.Y);
                float fYAngle = ((float)e.Location.X - (float)_ptPrevMousePosition.X);

                _ptPrevMousePosition = e.Location;

                _oglScene.Rotate(fXAngle, fYAngle);

                return;
            } // if ((e.Button & MouseButtons.Left) == MouseButtons.Left)

            // Zoom
            if ((e.Button & MouseButtons.Middle) == MouseButtons.Middle)
            {
                _bInteractionInProgress = true;

                float fZTranslation = e.Location.Y - _ptPrevMousePosition.Y > 0 ? -0.02f : 0.02f;

                _ptPrevMousePosition = e.Location;

                _oglScene.Zoom(fZTranslation);

                return;
            } // if ((e.Button & MouseButtons.Middle) == MouseButtons.Middle)

            // Move
            if ((e.Button & MouseButtons.Right) == MouseButtons.Right)
            {
                _bInteractionInProgress = true;

                float fXTranslation = (((float)e.Location.X - (float)_ptPrevMousePosition.X) / openGLControl.Width) * 10f;
                float fYTranslation = (((float)e.Location.Y - (float)_ptPrevMousePosition.Y) / openGLControl.Height) * 10f;

                _ptPrevMousePosition = e.Location;

                _oglScene.Move(fXTranslation, -fYTranslation);

                return;
            } // if ((e.Button & MouseButtons.Middle) == MouseButtons.Middle)
        }

        private void openGLControl_MouseWheel(object sender, MouseEventArgs e)
        {
            _oglScene.Zoom(e.Delta > 0);
        }

        private void modelStructureStripMenuItem_Click(object sender, EventArgs e)
        {
            if (_modelStructureForm.Visible)
            {
                _modelStructureForm.Hide();
            }
            else
            {
                _modelStructureForm = new ModelStructureForm();
                _modelStructureForm.SetController(this);
                _modelStructureForm.Show(this);
            }
        }

        private void viewToolStripMenuItem_Click(object sender, EventArgs e)
        {
            modelStructureStripMenuItem.Checked = _modelStructureForm.Visible;
        }

        public void RegisterView(IView view)
        {
            Debug.Assert(view != null);
            Debug.Assert(!_hsViews.Contains(view));

            _hsViews.Add(view);
        }

        public void UnRegisterView(IView view)
        {
            Debug.Assert(view != null);
            Debug.Assert(_hsViews.Contains(view));

            _hsViews.Remove(view);
        }

        public void SelectInstance(object sender, IInstance instance)
        {
            _oglScene.OnInstanceSelected(sender, instance);

            foreach (var view in _hsViews)
            {
                view.OnInstanceSelected(sender, instance);
            }

            // 同步TrView_IFCBuid的选择
            if (sender != _ifcBuildStructureView)
            {
                _ifcBuildStructureView?.OnInstanceSelected(sender, instance);
            }

            // 新增：当选择构件时，自动加载其属性到ListView
            if (instance != null && _model?.Type == ModelType.IFC)
            {
                LoadInstancePropertiesToListView(instance);
            }
            else
            {
                // 清空属性显示
                Lv_IfcPro.Items.Clear();
                _currentSelectedInstance = null;
                _propertyCategories.Clear();
            }
        }

        public void ZoomTo(IInstance instance)
        {
            Model.ZoomTo(instance);

            _oglScene.OnWorldDimensionsChanged();

            foreach (var view in _hsViews)
            {
                view.OnWorldDimensionsChanged();
            }
        }

        public void ZoomExtent()
        {
            Model.ZoomExtent();

            _oglScene.OnWorldDimensionsChanged();

            foreach (var view in _hsViews)
            {
                view.OnWorldDimensionsChanged();
            }
        }

        private void openGLControl_DragDrop(object sender, DragEventArgs e)
        {
            string[] files = (string[])e.Data.GetData(DataFormats.FileDrop);
            if (files.Length >= 1)
            {
                if (CreateModel(files[0]))
                {
                    LoadModel(files[0]);
                }
            }
        }

        private void openGLControl_DragEnter(object sender, DragEventArgs e)
        {
            if (e.Data.GetDataPresent(DataFormats.FileDrop))
            {
                e.Effect = DragDropEffects.Copy;
            }
        }

        // 导出ifc
        private void ExportToolMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                using (SaveFileDialog sfd = new SaveFileDialog())
                {
                    sfd.Title = "导出IFC文件";
                    sfd.Filter = "IFC 文件 (*.ifc)|*.ifc";
                    sfd.DefaultExt = "ifc";
                    sfd.AddExtension = true;
                    sfd.FileName = "导出模型.ifc"; // 默认文件名

                    if (sfd.ShowDialog() == DialogResult.OK)
                    {
                        string filePath = sfd.FileName;
                        _model.ExportIfc(filePath);
                        MessageBox.Show("导出成功：" + filePath, "提示",  MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                }
            }
            catch (System.Exception ex)
            {
                MessageBox.Show("导出失败：" + ex.Message, "错误",
                                MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        public DZJIFC.Model.Model Model
        {
            get
            {
                return _model;
            }
        }

        /// <summary>
        /// 提取基础属性
        /// Extract basic properties
        /// </summary>
        private void ExtractBasicProperties(int_t iInstance)
        {
            var basicProperties = new List<IFCProperty>();

            // IFC类型
            int_t iType = stepengine.sdaiGetInstanceType(iInstance);
            stepengine.engiGetEntityName(iType, stepengine.sdaiUNICODE, out IntPtr type);
            string ifcType = Marshal.PtrToStringUni(type) ?? "Unknown";
            basicProperties.Add(new IFCProperty("IFC类型", "IfcType", ifcType, "", "EntityType"));

            // Express ID
            long expressId = stepengine.internalGetP21Line(iInstance);
            basicProperties.Add(new IFCProperty("Express ID", "ExpressId", expressId.ToString(), "", "Integer"));

            // 名称
            stepengine.sdaiGetAttrBN(iInstance, "Name", stepengine.sdaiUNICODE, out IntPtr name);
            string strName = Marshal.PtrToStringUni(name) ?? "";
            if (!string.IsNullOrEmpty(strName))
            {
                basicProperties.Add(new IFCProperty("名称", "Name", strName, "", "String"));
            }

            // 描述
            stepengine.sdaiGetAttrBN(iInstance, "Description", stepengine.sdaiUNICODE, out IntPtr description);
            string strDescription = Marshal.PtrToStringUni(description) ?? "";
            if (!string.IsNullOrEmpty(strDescription))
            {
                basicProperties.Add(new IFCProperty("描述", "Description", strDescription, "", "String"));
            }

            // 标签
            stepengine.sdaiGetAttrBN(iInstance, "Tag", stepengine.sdaiUNICODE, out IntPtr tag);
            string strTag = Marshal.PtrToStringUni(tag) ?? "";
            if (!string.IsNullOrEmpty(strTag))
            {
                basicProperties.Add(new IFCProperty("标签", "Tag", strTag, "", "String"));
            }

            // GUID
            stepengine.sdaiGetAttrBN(iInstance, "GlobalId", stepengine.sdaiUNICODE, out IntPtr globalId);
            string strGlobalId = Marshal.PtrToStringUni(globalId) ?? "";
            if (!string.IsNullOrEmpty(strGlobalId))
            {
                basicProperties.Add(new IFCProperty("全局ID", "GlobalId", strGlobalId, "", "GUID"));
            }

            _propertyCategories["基础属性 (Basic Properties)"] = basicProperties;
        }

        /// <summary>
        /// 提取属性集属性
        /// Extract property set properties
        /// </summary>
        private void ExtractPropertySetProperties(int_t iInstance)
        {
            stepengine.sdaiGetAttrBN(iInstance, "IsDefinedBy", stepengine.sdaiAGGR, out IntPtr definedByInstances);
            if (definedByInstances == IntPtr.Zero) return;

            int_t iDefinedByCount = stepengine.sdaiGetMemberCount((int_t)definedByInstances);
            for (int_t iDefinedBy = 0; iDefinedBy < iDefinedByCount; iDefinedBy++)
            {
                int_t iDefinedByInstance = 0;
                stepengine.engiGetAggrElement((int_t)definedByInstances, iDefinedBy, stepengine.sdaiINSTANCE, out iDefinedByInstance);

                if (IsInstanceOf(iDefinedByInstance, "IFCRELDEFINESBYPROPERTIES"))
                {
                    stepengine.sdaiGetAttrBN(iDefinedByInstance, "RelatingPropertyDefinition", stepengine.sdaiINSTANCE, out IntPtr propertyInstances);
                    
                    if (IsInstanceOf((int_t)propertyInstances, "IFCPROPERTYSET"))
                    {
                        ExtractPropertiesFromPropertySet((int_t)propertyInstances);
                    }
                }
            }
        }

        /// <summary>
        /// 从属性集中提取属性
        /// Extract properties from property set
        /// </summary>
        private void ExtractPropertiesFromPropertySet(int_t iPropertySet)
        {
            // 获取属性集名称
            stepengine.sdaiGetAttrBN(iPropertySet, "Name", stepengine.sdaiUNICODE, out IntPtr psName);
            string propertySetName = Marshal.PtrToStringUni(psName) ?? "未知属性集";

            var properties = new List<IFCProperty>();

            stepengine.sdaiGetAttrBN(iPropertySet, "HasProperties", stepengine.sdaiAGGR, out IntPtr propertiesInstance);
            if (propertiesInstance == IntPtr.Zero) return;

            int_t iPropertiesCount = stepengine.sdaiGetMemberCount((int_t)propertiesInstance);
            for (int_t iProperty = 0; iProperty < iPropertiesCount; iProperty++)
            {
                int_t iPropertyInstance = 0;
                stepengine.engiGetAggrElement((int_t)propertiesInstance, iProperty, stepengine.sdaiINSTANCE, out iPropertyInstance);

                if (IsInstanceOf(iPropertyInstance, "IFCPROPERTYSINGLEVALUE"))
                {
                    var property = ExtractSingleValueProperty(iPropertyInstance);
                    if (property != null)
                    {
                        properties.Add(property);
                    }
                }
                else if (IsInstanceOf(iPropertyInstance, "IFCPROPERTYENUMERATEDVALUE"))
                {
                    var property = ExtractEnumeratedValueProperty(iPropertyInstance);
                    if (property != null)
                    {
                        properties.Add(property);
                    }
                }
                else if (IsInstanceOf(iPropertyInstance, "IFCPROPERTYBOUNDEDVALUE"))
                {
                    var property = ExtractBoundedValueProperty(iPropertyInstance);
                    if (property != null)
                    {
                        properties.Add(property);
                    }
                }
            }

            if (properties.Count > 0)
            {
                _propertyCategories[propertySetName] = properties;
            }
        }

        /// <summary>
        /// 提取单值属性
        /// Extract single value property
        /// </summary>
        private IFCProperty ExtractSingleValueProperty(int_t iPropertyInstance)
        {
            stepengine.sdaiGetAttrBN(iPropertyInstance, "Name", stepengine.sdaiUNICODE, out IntPtr namePtr);
            string name = Marshal.PtrToStringUni(namePtr) ?? "";

            stepengine.sdaiGetAttrBN(iPropertyInstance, "NominalValue", stepengine.sdaiUNICODE, out IntPtr valuePtr);
            string value = Marshal.PtrToStringUni(valuePtr) ?? "";

            stepengine.sdaiGetAttrBN(iPropertyInstance, "Unit", stepengine.sdaiUNICODE, out IntPtr unitPtr);
            string unit = Marshal.PtrToStringUni(unitPtr) ?? "";

            return new IFCProperty("", name, value, unit, "SingleValue");
        }

        /// <summary>
        /// 提取枚举值属性
        /// Extract enumerated value property
        /// </summary>
        private IFCProperty ExtractEnumeratedValueProperty(int_t iPropertyInstance)
        {
            stepengine.sdaiGetAttrBN(iPropertyInstance, "Name", stepengine.sdaiUNICODE, out IntPtr namePtr);
            string name = Marshal.PtrToStringUni(namePtr) ?? "";

            stepengine.sdaiGetAttrBN(iPropertyInstance, "EnumerationValues", stepengine.sdaiAGGR, out IntPtr enumValuesPtr);
            string value = "";
            if (enumValuesPtr != IntPtr.Zero)
            {
                int_t count = stepengine.sdaiGetMemberCount((int_t)enumValuesPtr);
                var values = new List<string>();
                for (int_t i = 0; i < count; i++)
                {
                    stepengine.engiGetAggrElement((int_t)enumValuesPtr, i, stepengine.sdaiUNICODE, out IntPtr valPtr);
                    string val = Marshal.PtrToStringUni(valPtr) ?? "";
                    if (!string.IsNullOrEmpty(val)) values.Add(val);
                }
                value = string.Join(", ", values);
            }

            return new IFCProperty("", name, value, "", "EnumeratedValue");
        }

        /// <summary>
        /// 提取区间值属性
        /// Extract bounded value property
        /// </summary>
        private IFCProperty ExtractBoundedValueProperty(int_t iPropertyInstance)
        {
            stepengine.sdaiGetAttrBN(iPropertyInstance, "Name", stepengine.sdaiUNICODE, out IntPtr namePtr);
            string name = Marshal.PtrToStringUni(namePtr) ?? "";

            stepengine.sdaiGetAttrBN(iPropertyInstance, "UpperBoundValue", stepengine.sdaiUNICODE, out IntPtr upperPtr);
            string upper = Marshal.PtrToStringUni(upperPtr) ?? "";

            stepengine.sdaiGetAttrBN(iPropertyInstance, "LowerBoundValue", stepengine.sdaiUNICODE, out IntPtr lowerPtr);
            string lower = Marshal.PtrToStringUni(lowerPtr) ?? "";

            stepengine.sdaiGetAttrBN(iPropertyInstance, "Unit", stepengine.sdaiUNICODE, out IntPtr unitPtr);
            string unit = Marshal.PtrToStringUni(unitPtr) ?? "";

            string value = $"[{lower} ~ {upper}]";
            return new IFCProperty("", name, value, unit, "BoundedValue");
        }

        /// <summary>
        /// 提取数量属性
        /// Extract quantity properties
        /// </summary>
        private void ExtractQuantityProperties(int_t iInstance)
        {
            stepengine.sdaiGetAttrBN(iInstance, "IsDefinedBy", stepengine.sdaiAGGR, out IntPtr definedByInstances);
            if (definedByInstances == IntPtr.Zero) return;

            int_t iDefinedByCount = stepengine.sdaiGetMemberCount((int_t)definedByInstances);
            for (int_t iDefinedBy = 0; iDefinedBy < iDefinedByCount; iDefinedBy++)
            {
                int_t iDefinedByInstance = 0;
                stepengine.engiGetAggrElement((int_t)definedByInstances, iDefinedBy, stepengine.sdaiINSTANCE, out iDefinedByInstance);

                if (IsInstanceOf(iDefinedByInstance, "IFCRELDEFINESBYPROPERTIES"))
                {
                    stepengine.sdaiGetAttrBN(iDefinedByInstance, "RelatingPropertyDefinition", stepengine.sdaiINSTANCE, out IntPtr propertyInstances);
                    
                    if (IsInstanceOf((int_t)propertyInstances, "IFCELEMENTQUANTITY"))
                    {
                        ExtractQuantitiesFromElementQuantity((int_t)propertyInstances);
                    }
                }
            }
        }

        /// <summary>
        /// 从元素数量集中提取数量
        /// Extract quantities from element quantity
        /// </summary>
        private void ExtractQuantitiesFromElementQuantity(int_t iElementQuantity)
        {
            // 获取数量集名称
            stepengine.sdaiGetAttrBN(iElementQuantity, "Name", stepengine.sdaiUNICODE, out IntPtr qsName);
            string quantitySetName = Marshal.PtrToStringUni(qsName) ?? "数量属性";

            var quantities = new List<IFCProperty>();

            stepengine.sdaiGetAttrBN(iElementQuantity, "Quantities", stepengine.sdaiAGGR, out IntPtr quantitiesInstance);
            if (quantitiesInstance == IntPtr.Zero) return;

            int_t iQuantitiesCount = stepengine.sdaiGetMemberCount((int_t)quantitiesInstance);
            for (int_t iQuantity = 0; iQuantity < iQuantitiesCount; iQuantity++)
            {
                stepengine.engiGetAggrElement((int_t)quantitiesInstance, iQuantity, stepengine.sdaiINSTANCE, out int_t iQuantityInstance);

                var quantity = ExtractQuantityProperty(iQuantityInstance);
                if (quantity != null)
                {
                    quantities.Add(quantity);
                }
            }

            if (quantities.Count > 0)
            {
                _propertyCategories[$"{quantitySetName} (Quantities)"] = quantities;
            }
        }

        /// <summary>
        /// 提取数量属性
        /// Extract quantity property
        /// </summary>
        private IFCProperty ExtractQuantityProperty(int_t iQuantityInstance)
        {
            // 数量名称
            stepengine.sdaiGetAttrBN(iQuantityInstance, "Name", stepengine.sdaiUNICODE, out IntPtr quantityName);
            string name = Marshal.PtrToStringUni(quantityName) ?? "";

            string value = "";
            string unit = "";
            string type = "";

            if (IsInstanceOf(iQuantityInstance, "IFCQUANTITYLENGTH"))
            {
                stepengine.sdaiGetAttrBN(iQuantityInstance, "LengthValue", stepengine.sdaiUNICODE, out IntPtr lengthValue);
                value = Marshal.PtrToStringUni(lengthValue) ?? "";
                unit = "m"; // 默认单位
                type = "Length";
            }
            else if (IsInstanceOf(iQuantityInstance, "IFCQUANTITYAREA"))
            {
                stepengine.sdaiGetAttrBN(iQuantityInstance, "AreaValue", stepengine.sdaiUNICODE, out IntPtr areaValue);
                value = Marshal.PtrToStringUni(areaValue) ?? "";
                unit = "m²";
                type = "Area";
            }
            else if (IsInstanceOf(iQuantityInstance, "IFCQUANTITYVOLUME"))
            {
                stepengine.sdaiGetAttrBN(iQuantityInstance, "VolumeValue", stepengine.sdaiUNICODE, out IntPtr volumeValue);
                value = Marshal.PtrToStringUni(volumeValue) ?? "";
                unit = "m³";
                type = "Volume";
            }
            else if (IsInstanceOf(iQuantityInstance, "IFCQUANTITYCOUNT"))
            {
                stepengine.sdaiGetAttrBN(iQuantityInstance, "CountValue", stepengine.sdaiUNICODE, out IntPtr countValue);
                value = Marshal.PtrToStringUni(countValue) ?? "";
                unit = "";
                type = "Count";
            }
            else if (IsInstanceOf(iQuantityInstance, "IFCQUANTITYWEIGHT"))
            {
                stepengine.sdaiGetAttrBN(iQuantityInstance, "WeightValue", stepengine.sdaiUNICODE, out IntPtr weightValue);
                value = Marshal.PtrToStringUni(weightValue) ?? "";
                unit = "kg";
                type = "Weight";
            }

            if (!string.IsNullOrEmpty(name) && !string.IsNullOrEmpty(value))
            {
                return new IFCProperty("", name, value, unit, type);
            }

            return null;
        }

        /// <summary>
        /// 提取材料属性
        /// Extract material properties
        /// </summary>
        private void ExtractMaterialProperties(int_t iInstance)
        {
            var materials = new List<IFCProperty>();

            stepengine.sdaiGetAttrBN(iInstance, "HasAssociations", stepengine.sdaiAGGR, out IntPtr associations);
            if (associations == IntPtr.Zero) return;

            int_t iAssociationsCount = stepengine.sdaiGetMemberCount((int_t)associations);
            for (int_t iAssoc = 0; iAssoc < iAssociationsCount; iAssoc++)
            {
                int_t iAssocInstance = 0;
                stepengine.engiGetAggrElement((int_t)associations, iAssoc, stepengine.sdaiINSTANCE, out iAssocInstance);

                if (IsInstanceOf(iAssocInstance, "IFCRELASSOCIATESMATERIAL"))
                {
                    stepengine.sdaiGetAttrBN(iAssocInstance, "RelatingMaterial", stepengine.sdaiINSTANCE, out IntPtr material);
                    if (material != IntPtr.Zero)
                    {
                        var materialProperty = ExtractMaterialInfo((int_t)material);
                        if (materialProperty != null)
                        {
                            materials.Add(materialProperty);
                        }
                    }
                }
            }

            if (materials.Count > 0)
            {
                _propertyCategories["材料属性 (Material Properties)"] = materials;
            }
        }

        /// <summary>
        /// 提取材料信息
        /// Extract material information
        /// </summary>
        private IFCProperty ExtractMaterialInfo(int_t iMaterial)
        {
            stepengine.sdaiGetAttrBN(iMaterial, "Name", stepengine.sdaiUNICODE, out IntPtr materialName);
            string name = Marshal.PtrToStringUni(materialName) ?? "";

            stepengine.sdaiGetAttrBN(iMaterial, "Description", stepengine.sdaiUNICODE, out IntPtr materialDesc);
            string description = Marshal.PtrToStringUni(materialDesc) ?? "";

            stepengine.sdaiGetAttrBN(iMaterial, "Category", stepengine.sdaiUNICODE, out IntPtr materialCategory);
            string category = Marshal.PtrToStringUni(materialCategory) ?? "";

            if (!string.IsNullOrEmpty(name))
            {
                string value = name;
                if (!string.IsNullOrEmpty(description))
                {
                    value += $" ({description})";
                }
                if (!string.IsNullOrEmpty(category))
                {
                    value += $" [{category}]";
                }

                return new IFCProperty("", "材料名称 (Material)", value, "", "Material");
            }

            return null;
        }

        /// <summary>
        /// 提取几何属性
        /// Extract geometry properties
        /// </summary>
        private void ExtractGeometryProperties(int_t iInstance)
        {
            var geometryProperties = new List<IFCProperty>();

            if (_currentSelectedInstance != null && _currentSelectedInstance.Geometry != null)
            {
                var geometry = _currentSelectedInstance.Geometry;

                // 几何表示类型
                geometryProperties.Add(new IFCProperty("", "几何表示", 
                    geometry.HasGeometry ? "有几何" : "无几何", "", "Boolean"));

                // 如果有几何信息，提取更多详细信息
                if (geometry.HasGeometry)
                {
                    // 这里可以添加更多几何属性的提取逻辑
                    // 例如：边界框、体积、表面积等
                    
                    // 占位符：几何类型
                    geometryProperties.Add(new IFCProperty("", "几何类型", "BRep", "", "GeometryType"));
                }
            }

            if (geometryProperties.Count > 0)
            {
                _propertyCategories["几何属性 (Geometry Properties)"] = geometryProperties;
            }
        }

        /// <summary>
        /// 在ListView中显示属性
        /// Display properties in ListView
        /// </summary>
        private void DisplayPropertiesInListView()
        {
            Lv_IfcPro.Items.Clear();

            foreach (var category in _propertyCategories)
            {
                string categoryName = category.Key;
                var properties = category.Value;

                // 添加分类标题项（使用特殊样式）
                var categoryItem = new ListViewItem(categoryName);
                categoryItem.SubItems.Add("");
                categoryItem.SubItems.Add($"[{properties.Count} 个属性]");
                categoryItem.SubItems.Add("");
                categoryItem.SubItems.Add("Category");
                categoryItem.Font = new Font(Lv_IfcPro.Font, FontStyle.Bold);
                categoryItem.BackColor = Color.LightGray;
                categoryItem.Tag = null; // 分类项没有对应的属性对象
                Lv_IfcPro.Items.Add(categoryItem);

                // 添加该分类下的所有属性
                foreach (var property in properties)
                {
                    var propertyItem = new ListViewItem($"  {categoryName}");
                    propertyItem.SubItems.Add(property.DisplayName);
                    propertyItem.SubItems.Add(property.Value);
                    propertyItem.SubItems.Add(property.Unit);
                    propertyItem.SubItems.Add(property.Type);
                    propertyItem.Tag = property;
                    Lv_IfcPro.Items.Add(propertyItem);
                }
            }

            // 自动调整列宽
            for (int i = 0; i < Lv_IfcPro.Columns.Count; i++)
            {
                Lv_IfcPro.AutoResizeColumn(i, ColumnHeaderAutoResizeStyle.ColumnContent);
            }
        }

        /// <summary>
        /// 检查实例是否为指定类型
        /// Check if instance is of specified type
        /// </summary>
        private bool IsInstanceOf(int_t iInstance, string strType)
        {
            if (_model?.Type == ModelType.IFC)
            {
                var ifcModel = _model as IFCModel;
                return stepengine.sdaiGetInstanceType(iInstance) == stepengine.sdaiGetEntity(ifcModel.Instance, strType);
            }
            return false;
        }
    }
}
